/*
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 * Copyright (c) 2023-2024 Jeremy Long. All Rights Reserved.
 */
package io.github.jeremylong.openvulnerability.client.epss;

import org.apache.hc.client5.http.impl.classic.AbstractHttpClientResponseHandler;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpEntity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;

public class EpssResponseHandler extends AbstractHttpClientResponseHandler<List<EpssItem>> {
    public EpssResponseHandler() {
        super();
    }

    @Override
    public List<EpssItem> handleResponse(ClassicHttpResponse response) throws IOException {
        return super.handleResponse(response);
    }

    @Override
    public List<EpssItem> handleEntity(HttpEntity entity) throws IOException {
        List<EpssItem> list = new ArrayList<>();
        try (InputStream is = entity.getContent();
                GZIPInputStream gis = new GZIPInputStream(is);
                Reader reader = new InputStreamReader(gis, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(reader)) {
            String line;
            int idx = 0;
            while ((line = br.readLine()) != null) {
                idx += 1;
                // two lines of headers
                if (idx <= 2) {
                    continue;
                }
                try {
                    String[] data = line.split(",");
                    EpssItem score = new EpssItem(data[0], Double.parseDouble(data[1]), Double.parseDouble((data[2])));
                    list.add(score);
                } catch (NumberFormatException | ArrayIndexOutOfBoundsException ex) {
                    throw new EpssException("Unable to parse EPSS CSV", ex);
                }
            }
            return list;
        }
    }
}
